<template>
  <div v-if="custom">
    <div class="action">
      <a-button size="small" @click="open" :disabled="$attrs.disabled">
        <template #icon>
          <plus-outlined/>
        </template>
        {{ trans('SelectTable.select') }}
      </a-button>
      <a-button size="small" v-if="selectValue" @click="clear"  :disabled="$attrs.disabled">
        <template #icon>
          <delete-outlined />
        </template>
        {{ trans('SelectTable.clear') }}
      </a-button>
    </div>
    <render :data="customRender"></render>
  </div>
  <span v-else-if="quick" @click="open">
    <slot>
      <a-button size="small" :disabled="$attrs.disabled">
        <template #icon>
          <plus-outlined/>
        </template>
        {{ trans('SelectTable.select') }}
      </a-button>
    </slot>
  </span>
  <div v-else>
    <a-select v-bind="$attrs" v-model:value="selectValue" :options="options" allow-clear :open="false" @click="open">
    </a-select>
  </div>
  <a-modal v-model:visible="visible" width="80%" destroyOnClose>
    <a-form-item-rest>
      <render :data="content" v-model:selection="selection" :scroll="height" :hideSelection="false"
              :selection-type="multiple ? 'checkbox':'radio'"></render>
    </a-form-item-rest>
    <template #footer>
      <div :class="multiple && selection.length > 0 ? 'footer':''">
        <div v-if="multiple && selection.length > 0">{{ trans('SelectTable.selected') }}: {{ selection.length }}</div>
        <div>
          <a-button type="primary" @click="throttleSubmit">{{ trans('SelectTable.confirm') }}</a-button>
          <a-button @click="visible = false">{{ trans('SelectTable.cancel') }}</a-button>
        </div>
      </div>
    </template>
  </a-modal>
</template>

<script>
import {useInjectFormContext} from '@/components/form/context'
import {useInjectGridContext} from '@/components/grid/context'
import {trans,empty} from '@/utils'
import {defineComponent, ref, watch} from "vue";
import {throttle} from "lodash";
import ajax from '@/utils/ajax.js'
import {action} from "@/store";

export default defineComponent({
  name: "ExSelectTable",
  props: {
    value: [String, Array, Number],
    params: Object,
    gridUrl: String,
    submitUrl: String,
    remoteParams: {
      type: Object,
      default: {}
    },
    submitParams: {
      type: Object,
      default: {}
    },
    custom: Boolean,
    quick: Boolean,
    multiple: Boolean,
    gridRefresh: Boolean,
    modalRefresh: Boolean,
    gridBatch: Boolean,
  },
  inheritAttrs: false,
  emits: ['update:value'],
  setup(props, ctx) {
    const grid  = useInjectGridContext()
    const formContext = useInjectFormContext()
    const selectValue = ref(props.multiple ? [...props.value]:props.value)
    const visible = ref(false)
    const options = ref([])
    const customRender = ref(null)
    const selection = ref(props.value || [])
    const content = ref('')
    if (!Array.isArray(selection.value)) {
      selection.value = [selection.value]
    }
    const height = {
      x: 'max-content',
      y: window.innerHeight / 2
    }
    if (props.submitUrl && !empty(props.value)) {
      submit()
    }
    watch(() => props.value, val => {
      selectValue.value = val

    })
    watch(selectValue, (val) => {
      if (props.multiple) {
        selection.value = val
      } else {
        if (val) {
          selection.value = [val]
        } else {
          selection.value = []
        }
      }
      ctx.emit('update:value', val)
      if(selection.value.length > 0){
        throttleSubmit()
      }
    })

    function open() {
      if (props.gridUrl) {
        content.value = null
        visible.value = true
        ajax({
          url: props.gridUrl,
          method: 'POST',
          data: props.params
        }).then(res => {
          Object.assign(res.attribute.params, props.params)
          content.value = res
        })
      }
    }
    const throttleSubmit = throttle(submit,500, { 'trailing': false })
    function submit() {
      let params = Object.assign(props.submitParams, {ex_eadmin_select_id: selection.value})
      if(formContext){
        params.data = formContext.submitData()
      }
      let gridSelected = []
      if(props.gridBatch){
        gridSelected = grid.exposed.selectIds.value
      }
      if(props.submitUrl){
        ajax({
          url: props.submitUrl,
          method: 'POST',
          data: params,
        },props.gridBatch,gridSelected).then(res => {
          if(props.quick){
            if(props.gridRefresh){
              grid.exposed.refresh()
            }
            if(props.modalRefresh){
              action.modalRefresh()
            }
            visible.value = false
            return
          }
          if (props.custom) {
            customRender.value = res.data
          } else {
            options.value = res.data
          }
          emitValue()
        })
      }else{
        emitValue()
      }
    }
    function emitValue(){
      visible.value = false
      const selects = []
      selection.value.forEach(item => {
        selects.push(item)
      })
      if (props.multiple) {

        selectValue.value = selects
      } else {
        let val = selects.pop()
        if (typeof (val) !== 'undefined') {
          selectValue.value = val
        }
      }
    }
    function clear(){
      if (props.multiple) {
        selectValue.value = []
      }else{
        selectValue.value = null
      }
    }
    return {
      submit,
      clear,
      trans,
      throttleSubmit,
      open,
      content,
      options,
      selectValue,
      selection,
      visible,
      height,
      customRender
    }
  }
})
</script>

<style scoped>
.flex {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.action{
  display: flex;
  align-items: center;
  margin:5px 0;
}
.footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
